<template>
	<div class="box">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="账号登录" name="first">
				<div class="slot">
					<el-input class="account" placeholder="请输入账号" prefix-icon="el-icon-user" v-model="accountNumber"
						:clearable="true">
					</el-input>
					<el-input class="pswd" placeholder="请输入密码" prefix-icon="el-icon-lock" v-model="pswd"
						:show-password="true" :clearable="true">
					</el-input>
					<!-- <div>
            <span class="login">验证：</span>
            <input style="width: 100px" type="text" placeholder="请输入验证码" class="input-val" v-model.trim="yanzhen"
              @keyup.enter="login_enter" />
            <canvas id="canvas" width="130px" height="33px" @click="handleCanvas"> </canvas>
          </div> -->

					<div class="yanZhenBox">
						<el-input type="text" placeholder="请输入验证码" maxlength="4" class="input-val"
							v-model.trim="yanzhen" @keyup.enter.native="Logging('账号登录')">
							<div slot="prefix" class="prefixIcon">
								<i class="iconfont icon-yanzhengma"></i>
							</div>
							<div slot="suffix" class="canvasBox">
								<canvas id="canvas" @click="handleCanvas"> </canvas>
							</div>
						</el-input>
					</div>

					<div class="control">
						<el-checkbox class="remember" v-model="checked" @change="isRemember()">记住账号</el-checkbox>
						<a class="forget" href="javascript:void(0);">忘记密码?</a>
					</div>
					<button class="loginBtn" @click="Logging('账号登录')">登录</button>
				</div>
			</el-tab-pane>
			<el-tab-pane label="验证码登录" name="second">
				<div class="slot">
					<el-input class="phoneInput" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone" v-model="phone"
						:clearable="true">
					</el-input>
					<el-input class="VerificationCode" placeholder="请输入验证码" v-model="verifyCode" :clearable="true"
						@keyup.enter.native="Logging('验证码登录')">
						<i slot="prefix" class="iconfont icon-yanzhengma"></i>
						<span v-show="showGetCode" class="getCode" slot="suffix"
							@click="getVerificationCode()">获取验证码</span>
						<span class="timing" v-show="!showGetCode" slot="suffix">重新发送({{ count }})</span>
					</el-input>
					<button class="loginBtn" style="margin-top: 47px" @click="Logging('验证码登录')">
						登录
					</button>
				</div>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script>
import httpApi from "@/http";
import store from "@/store/index";
export default {
	data() {
		return {
			activeName: "first",
			accountNumber: "",
			pswd: "",
			checked: false, //是否记住账号
			phone: "",
			verifyCode: "", //验证码
			timing: null,
			showGetCode: true,
			count: "", //验证码计时

			yanzhen: "", //输入框双向绑定的值
			true_code: "", //保存正确的验证码
			yanzhen_arr: [], //只用于传参，并且数组长度不能「多于」下面验证码遍历的次数，不然最终得到的true_code会有问题
			//比如下面是4个验证码，可以是[1,2,3,4]及以下，但是不能是[1，2，3，4，5]， 因为5无法被替换
			loading: false,
			value: '',
			key: ''
		};
	},
	methods: {
		smallLetter(yanzhen) {
			var str = yanzhen.split("");
			for (var i = 0; i < str.length; i++) {
				if (/^[A-Z]$/.test(str[i])) {
					str[i] = str[i].toLowerCase();
				}
			}
			this.yanzhen = str.join("");
		},
		Logging(type) {
			if (type == "账号登录") {
				//4位验证码校验
				// this.smallLetter(this.yanzhen); //全部转为小写字母
				// //console.log('正确验证', this.true_code);
				if (this.yanzhen != this.true_code) {
					this.$message.error("验证码错误");
					return;
				} else if (this.loading == true) {
					this.$message.warning('请勿频繁点击,正在登录中')
					return
				}
				this.loading = true
				//console.log('点击了一次登录');
				let pswd = this.Rsa.encrypt(this.pswd)
				let params = {
					username: this.accountNumber,
					password: pswd,
					captchaVo: {
						value: this.yanzhen,
						key: this.key,
					},
					type: "0",
				};
				httpApi.loginApi.loginuser(params).then((res) => {
					//console.log("登录结果", res);
					//console.log(res.data.code);
					if (res.data.code == 200 && this.checked) {
						//code200 且 勾选记住账号 存local
						this.$store.commit("saveToken", {
							token: res.data.data.access_token,
							checked: this.checked,
						});

						//console.log(res);
						//console.log("token", store.state.token,);
						this.$message({
							message: "登录成功",
							type: "success",
						});
						params.checked = this.checked;
						localStorage.setItem("saveUser", JSON.stringify(params));
						//console.log(this.$router);
						this.$router.push("/home/index");
					} else if (res.data.code == 200 && !this.checked) {
						//code200 且 未勾选记住账号  存session
						this.$store.commit("saveToken", {
							token: res.data.data.access_token,
							checked: !this.checked,
						});
						//console.log(res);
						//console.log("token", store.state.token);
						this.$message({
							message: "登录成功",
							type: "success",
						});
						//console.log(this.$router);
						localStorage.removeItem("saveUser");
						this.$router.push("/home/index");
					} else if (res.data.code == 500) {
						this.$message({
							message: res.data.msg,
							type: "error",
						});
					}
					this.loading = false
					this.handleCanvas();
				});
			} else if (type == "验证码登录") {
				if (this.loading == true) {
					this.$message.warning('请勿频繁点击,正在登录中')
					return
				}
				this.loading = true
				let params = {
					username: this.phone,
					code: this.verifyCode,
					type: "1",
				};

				httpApi.loginApi.loginuser(params).then((res) => {
					//console.log("登录结果", res);
					//console.log(res.data.code);
					if (res.data.code == 200 && this.checked) {
						//code200 且 勾选记住账号 存local
						this.$store.commit("saveToken", {
							token: res.data.data.access_token,
							checked: this.checked,
						});

						//console.log(res);
						//console.log("token", store.state.token,);
						this.$message({
							message: "登录成功",
							type: "success",
						});
						//console.log(this.$router);
						this.$router.push("/home/index");
					} else if (res.data.code == 200 && !this.checked) {
						//code200 且 未勾选记住账号  存session
						this.$store.commit("saveToken", {
							token: res.data.data.access_token,
							checked: !this.checked,
						});

						//console.log(res);
						//console.log("token", store.state.token);
						this.$message({
							message: "登录成功",
							type: "success",
						});
						//console.log(this.$router);
						this.$router.push("/home/index");
					}
					this.loading = false
				});
			}
		},
		handleClick(tab, event) {
			// console.log(tab, event);
		},
		isRemember() { },
		// 验证码 发送计数
		getVerificationCode() {
			this.showGetCode = false;
			const TIME_COUNT = 60; //倒计时初始值10秒
			if (!this.timing) {
				this.count = TIME_COUNT;
				this.show = false;
				this.timing = setInterval(() => {
					if (this.count > 0 && this.count <= TIME_COUNT) {
						this.count--;
					} else {
						this.showGetCode = true;
						clearInterval(this.timing);
						this.timing = null;
					}
				}, 1000);
			}
			let params = {
				phone: this.phone,
				port: "CARGOOWNER_LOGIN",
			};
			httpApi.loginApi.getAuditCode(params).then((res) => {
				if (res.data.code == 200) {
					this.$message.success("获取验证码成功");
				}
			});
		},

		//20211115 新增验证码功能
		//显示验证码区域内容信息
		async draw() {
			var show_num = []
			var canvas_width = document.querySelector("#canvas").clientWidth;
			var canvas_height = document.querySelector("#canvas").clientHeight;
			var canvas = document.getElementById("canvas"); //获取到canvas
			var context = canvas.getContext("2d"); //获取到canvas画图
			canvas.width = canvas_width;
			canvas.height = canvas_height;
			var sCode =
				"a,b,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
			var aCode = sCode.split(",");
			var aLength = aCode.length; //获取到数组的长度

			//4个验证码数
			for (var i = 0; i <= this.value.length; i++) {
				var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
				var deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
				var txt = this.value[i]; //得到随机的一个内容

				// show_num[i] = txt.toLowerCase(); // 依次把取得的内容放到数组里面
				var x = 10 + i * 20; //文字在canvas上的x坐标
				var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
				context.font = "bold 23px 微软雅黑";
				context.translate(x, y);
				context.rotate(deg);
				context.fillStyle = this.randomColor();
				context.fillText(txt, 0, 0);
				context.rotate(-deg);
				context.translate(-x, -y);
			}
			//验证码上显示6条线条
			for (var i = 0; i <= 5; i++) {
				context.strokeStyle = this.randomColor();
				context.beginPath();
				context.moveTo(
					Math.random() * canvas_width,
					Math.random() * canvas_height
				);
				context.lineTo(
					Math.random() * canvas_width,
					Math.random() * canvas_height
				);
				context.stroke();
			}
			//验证码上显示31个小点
			for (var i = 0; i <= 30; i++) {
				context.strokeStyle = this.randomColor();
				context.beginPath();
				var x = Math.random() * canvas_width;
				var y = Math.random() * canvas_height;
				context.moveTo(x, y);
				context.lineTo(x + 1, y + 1);
				context.stroke();
			}

			//最后把取得的验证码数组存起来，方式不唯一
			var num = this.value
			console.log(num, 'num');
			this.true_code = num;
		},
		//得到随机的颜色值
		randomColor() {
			var r = Math.floor(Math.random() * 256);
			var g = Math.floor(Math.random() * 256);
			var b = Math.floor(Math.random() * 256);
			return "rgb(" + r + "," + g + "," + b + ")";
		},
		//canvas点击刷新
		handleCanvas() {
			this.draw();
		},
		async Huoqucode() {
			let res = await httpApi.loginApi.getCaptcha()
			this.value = res.data.data.value
			this.key = res.data.data.key
			console.log(res)
			this.draw()

		},
		getLocalStorage() {
			if (localStorage.getItem("saveUser")) {
				let User = JSON.parse(localStorage.getItem("saveUser"));
				console.log(User);
				this.accountNumber = User.username;
				this.pswd = User.password;
				this.checked = User.checked;
			}
		},
	},
	mounted() {
		this.Huoqucode()
		this.getLocalStorage();
	},
};
</script>

<style lang="scss" scoped>
.box {
	width: 360px;
	background-color: #fff;
	border-radius: 8px;
	padding: 31px 24px 32px;
	display: flex;

	.slot {
		>.remember {
			::v-deep .el-checkbox__label {
				font-size: 12px;
				color: #262626;
			}
		}

		>.phoneInput {
			height: 40px;
			margin-top: 23px;
			margin-bottom: 16px;

			::v-deep .el-icon-mobile-phone {
				font-size: 19px;
			}

			::v-deep .el-input__inner {
				height: 40px;
			}
		}

		>.VerificationCode {
			height: 40px;
			margin-bottom: 19px;

			::v-deep .el-input__prefix {
				margin-left: 2px;
				line-height: 40px;
			}

			::v-deep .el-input__inner {
				height: 40px;
			}

			.getCode {
				color: #1890ff;
				font-size: 14px;
				line-height: 40px;
				display: inline-block;
				margin-right: 13px;
				position: relative;
				z-index: 800;
				cursor: pointer;
			}

			.timing {
				color: #1890ff;
				font-size: 14px;
				line-height: 40px;
				margin-right: 13px;
			}

			.icon-yanzhengma {
				font-size: 18px;
			}
		}

		.loginBtn {
			background-color: #1890ff;
			height: 40px;
			width: 313px;
			border-radius: 4px;
			text-align: center;
			line-height: 40px;
			color: #fff;
			font-size: 14px;
			margin-top: 47px;
			cursor: pointer;
		}

		>.account {
			margin-top: 23px;
			height: 40px;

			::v-deep .el-input__inner {
				height: 40px;
			}
		}

		>.pswd {
			margin-top: 16px;

			::v-deep .el-input__inner {
				height: 40px;
			}
		}

		>.control {
			width: 100%;
			display: flex;
			margin-top: 19px;
			font-size: 12px;
			align-items: center;
			justify-content: space-between;

			.remember {
				::v-deep .el-checkbox__label {
					font-size: 12px;
					color: #262626;
				}
			}

			>.forget {
				color: #1890ff;
			}
		}
	}
}

.yanZhenBox {
	margin-top: 16px;

	.prefixIcon {
		// display: flex;
		// align-items: center;
		line-height: 40px;
		width: 25px;
		height: 40px;
		display: flex;
		justify-content: center;
		align-items: center;

		.icon-yanzhengma {
			font-size: 13px;
		}
	}

	.canvasBox {
		height: 40px;
		display: flex;
		align-items: center;

		#canvas {
			width: 92px;
			float: right;
			display: block;
			border: 1px solid #ccc;
			border-radius: 4px;
			height: 36px;
			cursor: pointer;
		}
	}
}
</style>